<?php

namespace app\company\model;


use Exception;
use think\Model;

/**
 * 企业角色
 * @property  int $id
 * @property  int $company_id
 */
class CompanyRole extends Base
{

    public static function onBeforeInsert(CompanyRole $model): void
    {
        $model->company_id = getCompanyId();
    }

    /**
     * @param CompanyRole $model
     * @return void
     * @throws Exception
     */
    public static function onAfterInsert(CompanyRole $model): void
    {
        // 添加角色权限
        self::addMenu($model);
    }


    /**
     * @param CompanyRole $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(CompanyRole $model): void
    {
        // 添加角色权限
        self::addMenu($model);
    }


    /**
     * @param CompanyRole $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(CompanyRole $model): void
    {
        if($ids = $model->companyRoleMenus()->column('id'))CompanyRoleMenu::destroy($ids,true);
    }


    /**
     * @param $model
     * @return void
     * @throws Exception
     */
    public static function addMenu($model): void
    {
        if($menu_ids = request()->param('menu_ids',0)){
            $arr = explode(',',$menu_ids);
            $data = [];
            foreach ($arr as $v){
                $array['company_role_id'] = $model->id;
                $array['company_menu_id'] = $v;
                $data[] = $array;
            }
            if($ids = $model->companyRoleMenus()->column('id'))CompanyRoleMenu::destroy($ids,true);
            (new CompanyRoleMenu())->saveAll($data);
        }
    }
}